/**
 * 主应用程序 - 负责模块切换、数据加载和用户交互
 */

class SupplyChainApp {
    constructor() {
        this.currentModule = 'dashboard';
        this.isLoading = false;
        this.refreshInterval = null;

        this.refreshIntervalTime = 30000; // 30秒
        
        this.init();
    }
    
    /**
     * 初始化应用
     */
    async init() {
        this.setupEventListeners();

        
        // 测试API连接
        await this.testAPIConnection();
        
        // 加载默认模块
        await this.loadModule(this.currentModule);
        
        // 设置定时刷新

    }
    
    /**
     * 设置事件监听器
     */
    setupEventListeners() {
        // 导航菜单点击事件
        document.querySelectorAll('.nav-link').forEach(link => {
            link.addEventListener('click', (e) => {
                e.preventDefault();
                const module = e.target.dataset.module;
                if (module) {
                    this.loadModule(module);
                }
            });
        });
        
        // 刷新按钮点击事件
        const refreshBtn = document.getElementById('refreshBtn');
        if (refreshBtn) {
            refreshBtn.addEventListener('click', () => {
                this.refreshCurrentModule();
            });
        }
        
        // 模态框关闭事件
        const modal = document.getElementById('detailModal');
        if (modal) {
            modal.addEventListener('click', (e) => {
                if (e.target === modal || e.target.classList.contains('close')) {
                    this.closeModal();
                }
            });
        }
        
        // ESC键关闭模态框
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape') {
                this.closeModal();
            }
        });
        
        // 自动刷新开关
        const autoRefreshToggle = document.getElementById('autoRefreshToggle');
        if (autoRefreshToggle) {
            autoRefreshToggle.addEventListener('change', (e) => {
                this.toggleAutoRefresh(e.target.checked);
            });
        }
    }
    

    
    /**
     * 测试API连接
     */
    async testAPIConnection() {
        try {
            await window.apiClient.testConnection();
        } catch (error) {
            console.error('API连接测试失败:', error);
        }
    }
    
    /**
     * 加载模块
     */
    async loadModule(moduleName) {
        if (this.isLoading) return;
        
        this.isLoading = true;
        this.currentModule = moduleName;
        
        // 更新导航状态
        this.updateNavigation(moduleName);
        
        // 显示对应的模块内容
        this.showModuleContent(moduleName);
        
        // 加载模块数据
        await this.loadModuleData(moduleName);
        
        this.isLoading = false;
    }
    
    /**
     * 导航到指定模块（用于KPI卡片点击）
     */
    navigateToModule(moduleName) {
        this.loadModule(moduleName);
    }
    
    /**
     * 更新导航状态
     */
    updateNavigation(activeModule) {
        document.querySelectorAll('.nav-link').forEach(link => {
            link.classList.remove('active');
            if (link.dataset.module === activeModule) {
                link.classList.add('active');
            }
        });
    }
    
    /**
     * 显示模块内容
     */
    showModuleContent(moduleName) {
        // 隐藏所有模块
        document.querySelectorAll('.module-content').forEach(module => {
            module.style.display = 'none';
        });
        
        // 显示当前模块
        const currentModuleElement = document.getElementById(`${moduleName}-content`);
        if (currentModuleElement) {
            currentModuleElement.style.display = 'block';
        } else {
            console.warn(`模块 ${moduleName}-content 不存在`);
        }
    }
    
    /**
     * 加载模块数据
     */
    async loadModuleData(moduleName) {
        try {
            switch (moduleName) {
                case 'dashboard':
                    await this.loadDashboardData();
                    break;
                case 'planning':
                    // 初始化计划管理模块
                    initPlanningModule();
                    break;
                case 'sourcing':
                    await this.loadSourcingData();
                    break;
                case 'manufacturing':
                    await this.loadManufacturingData();
                    break;
                case 'delivery':
                    await this.loadDeliveryData();
                    break;
                case 'intelligence':
                    // 智能化功能模块 - 功能开发中
                    break;
                case 'analytics':
                    await this.loadAnalyticsData();
                    break;
                case 'mobile':
                    // 移动应用模块 - 功能开发中
                    break;
                case 'innovation':
                    // 创新技术模块 - 功能开发中
                    break;
                default:
                    console.warn(`未知模块: ${moduleName}`);
            }
        } catch (error) {
            console.error(`加载${moduleName}模块数据失败:`, error);
            this.showError(`加载${moduleName}模块数据失败`);
        }
    }
    
    /**
     * 加载仪表板数据
     */
    async loadDashboardData() {
        try {
            // 加载KPI数据
            const kpiData = await window.apiClient.getDashboardKPIs();
            this.updateKPICards(kpiData);
            
            // 加载图表数据
            const inventoryChartData = await window.apiClient.getInventoryChartData();
            window.chartManager.createInventoryChart('inventoryChart', inventoryChartData);
            
            const orderChartData = await window.apiClient.getOrderTrendChartData();
            window.chartManager.createOrderTrendChart('orderChart', orderChartData);
            
            // 加载采购数据图表
            const procurementData = await window.apiClient.getProcurementChartData();
            window.chartManager.createProcurementChart('procurementChart', procurementData);
            
            // 加载生产数据图表
            const productionData = await window.apiClient.getProductionChartData();
            window.chartManager.createProductionChart('productionChart', productionData);
            
            // 加载配送数据图表
            const deliveryData = await window.apiClient.getDeliveryChartData();
            window.chartManager.createDeliveryChart('deliveryChart', deliveryData);
            
            // 加载质量数据图表
            const qualityData = await window.apiClient.getQualityChartData();
            window.chartManager.createQualityChart('qualityChart', qualityData);
            
            // 加载业务活动数据
            const activitiesData = await window.apiClient.getBusinessActivities();
            this.updateActivitiesTable(activitiesData);
            
        } catch (error) {
            console.error('加载仪表板数据失败:', error);
        }
    }
    
    /**
     * 加载库存数据
     */
    async loadInventoryData() {
        try {
            // 加载库存统计
            const stats = await window.apiClient.getInventoryStats();
            this.updateInventoryStats(stats);
            
            // 加载库存列表
            const inventory = await window.apiClient.getInventoryData();
            this.updateInventoryTable(inventory);
            
            // 加载仓库列表
            const warehouses = await window.apiClient.getWarehouses();
            this.updateWarehouseSelect(warehouses);
            
            // 加载产品类别
            const categories = await window.apiClient.getProductCategories();
            this.updateCategorySelect(categories);
            
        } catch (error) {
            console.error('加载库存数据失败:', error);
        }
    }
    
    /**
     * 加载订单数据
     */
    async loadOrdersData() {
        try {
            // 加载订单统计
            const stats = await window.apiClient.getOrdersStats();
            this.updateOrdersStats(stats);
            
            // 加载订单列表
            const orders = await window.apiClient.getOrdersData();
            this.updateOrdersTable(orders);
            
        } catch (error) {
            console.error('加载订单数据失败:', error);
        }
    }
    
    /**
     * 加载智能分析数据
     */
    async loadAnalyticsData() {
        try {
            // 默认加载需求预测
            await this.loadForecastData();
            
            // 设置分析标签页事件
            this.setupAnalyticsTabs();
            
        } catch (error) {
            console.error('加载智能分析数据失败:', error);
        }
    }
    
    /**
     * 加载采购管理数据
     */
    async loadSourcingData() {
        try {
            // 加载采购相关数据
            const procurementData = await window.apiClient.get('/charts/procurement-performance');
            this.updateProcurementCharts(procurementData);
            
            // 加载供应商数据
            const supplierData = await window.apiClient.get('/procurement/suppliers');
            this.updateSupplierTable(supplierData);
            
        } catch (error) {
            console.error('加载采购管理数据失败:', error);
            this.showError('加载采购管理数据失败');
        }
    }
    
    /**
     * 加载生产管理数据
     */
    async loadManufacturingData() {
        try {
            // 加载生产效率数据
            const productionData = await window.apiClient.get('/charts/production-efficiency');
            this.updateProductionCharts(productionData);
            
            // 加载生产订单数据
            const orderData = await window.apiClient.get('/production/orders');
            this.updateProductionOrders(orderData);
            
        } catch (error) {
            console.error('加载生产管理数据失败:', error);
            this.showError('加载生产管理数据失败');
        }
    }
    
    /**
     * 加载配送管理数据
     */
    async loadDeliveryData() {
        try {
            // 加载配送绩效数据
            const deliveryData = await window.apiClient.get('/charts/delivery-performance');
            this.updateDeliveryCharts(deliveryData);
            
            // 加载物流数据
            const logisticsData = await window.apiClient.get('/logistics/shipments');
            this.updateLogisticsStatus(logisticsData);
            
        } catch (error) {
            console.error('加载配送管理数据失败:', error);
            this.showError('加载配送管理数据失败');
        }
    }
    
    /**
     * 加载质量数据
     */
    async loadQualityData() {
        try {
            // 加载质量仪表板
            const dashboard = await window.apiClient.getQualityDashboard();
            this.updateQualityDashboard(dashboard);
            
        } catch (error) {
            console.error('加载质量数据失败:', error);
        }
    }
    
    /**
     * 更新KPI卡片
     */
    updateKPICards(data) {
        if (!data || !data.kpis) return;
        
        const kpiGrid = document.getElementById('kpiGrid');
        if (!kpiGrid) return;
        
        // 生成KPI卡片HTML
        kpiGrid.innerHTML = data.kpis.map((kpi, index) => {
            // 确定图标
            let icon = 'fas fa-chart-line';
            if (kpi.title.includes('库存')) icon = 'fas fa-boxes';
            else if (kpi.title.includes('订单')) icon = 'fas fa-shopping-cart';
            else if (kpi.title.includes('供应商')) icon = 'fas fa-truck';
            else if (kpi.title.includes('周转')) icon = 'fas fa-sync-alt';
            
            // 确定跳转模块 - 根据KPI业务含义精准匹配
            let targetModule = 'analytics';
            if (kpi.title.includes('总库存价值')) targetModule = 'planning'; // 库存价值 -> 计划管理(库存计划)
            else if (kpi.title.includes('活跃订单')) targetModule = 'manufacturing'; // 活跃订单 -> 生产管理(订单执行)
            else if (kpi.title.includes('供应商数量')) targetModule = 'sourcing'; // 供应商 -> 采购管理
            else if (kpi.title.includes('库存周转率')) targetModule = 'delivery'; // 周转率 -> 配送管理(库存流转)
            
            return `
                <div class="kpi-card" onclick="app.navigateToModule('${targetModule}')" style="cursor: pointer;">
                    <div class="kpi-icon">
                        <i class="${icon}"></i>
                    </div>
                    <div class="kpi-content">
                        <div class="kpi-value">${kpi.value}</div>
                        <div class="kpi-label">${kpi.title}</div>
                        <div class="kpi-change ${kpi.trend === 'down' ? 'negative' : 'positive'}">
                            <i class="fas fa-arrow-${kpi.trend === 'down' ? 'down' : 'up'}"></i>
                            ${kpi.change || '+0%'}
                        </div>
                    </div>
                </div>
            `;
        }).join('');
    }
    
    /**
     * 更新活动表格
     */
    updateActivitiesTable(data) {
        const tbody = document.querySelector('#businessTableBody');
        if (!tbody || !data || !data.activities) return;
        
        tbody.innerHTML = data.activities.map(activity => `
            <tr>
                <td>${activity.time}</td>
                <td>${activity.type}</td>
                <td>${activity.description}</td>
                <td><span class="status-badge status-${activity.status}">${activity.statusText}</span></td>
                <td>
                    <button class="btn-action" onclick="viewDetails('${activity.id}')">
                        <i class="fas fa-eye"></i> 查看
                    </button>
                </td>
            </tr>
        `).join('');
    }
    
    /**
     * 更新库存统计
     */
    updateInventoryStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#inventoryStats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalItems || 0}</div>
                    <div class="stat-label">总商品数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.lowStockItems || 0}</div>
                    <div class="stat-label">低库存商品</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.outOfStockItems || 0}</div>
                    <div class="stat-label">缺货商品</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.totalValue || 0}</div>
                    <div class="stat-label">库存总值</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新库存表格
     */
    updateInventoryTable(data) {
        const tbody = document.querySelector('#inventoryTable tbody');
        if (!tbody || !data || !data.items) return;
        
        tbody.innerHTML = data.items.map(item => `
            <tr onclick="app.showItemDetail('${item.id}')" style="cursor: pointer;">
                <td>${item.sku}</td>
                <td>${item.name}</td>
                <td>${item.category}</td>
                <td>${item.quantity}</td>
                <td>${item.unit}</td>
                <td><span class="status-badge status-${item.status}">${item.statusText}</span></td>
                <td>${item.warehouse}</td>
                <td>¥${item.unitPrice}</td>
            </tr>
        `).join('');
    }
    
    /**
     * 更新订单统计
     */
    updateOrdersStats(data) {
        if (!data) return;
        
        const statsContainer = document.querySelector('#ordersStats');
        if (statsContainer) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.totalOrders || 0}</div>
                    <div class="stat-label">总订单数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.pendingOrders || 0}</div>
                    <div class="stat-label">待处理订单</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.completedOrders || 0}</div>
                    <div class="stat-label">已完成订单</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">¥${data.totalValue || 0}</div>
                    <div class="stat-label">订单总值</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新订单表格
     */
    updateOrdersTable(data) {
        const tbody = document.querySelector('#ordersTable tbody');
        if (!tbody || !data || !data.orders) return;
        
        tbody.innerHTML = data.orders.map(order => `
            <tr onclick="app.showOrderDetail('${order.id}')" style="cursor: pointer;">
                <td>${order.orderNumber}</td>
                <td>${order.customer}</td>
                <td>${order.date}</td>
                <td>¥${order.amount}</td>
                <td><span class="status-badge status-${order.status}">${order.statusText}</span></td>
                <td>${order.priority}</td>
            </tr>
        `).join('');
    }
    
    /**
     * 设置分析标签页
     */
    setupAnalyticsTabs() {
        document.querySelectorAll('.analytics-tab').forEach(tab => {
            tab.addEventListener('click', async (e) => {
                e.preventDefault();
                
                // 更新标签状态
                document.querySelectorAll('.analytics-tab').forEach(t => t.classList.remove('active'));
                tab.classList.add('active');
                
                // 加载对应数据
                const tabType = tab.dataset.tab;
                await this.loadAnalyticsTab(tabType);
            });
        });
    }
    
    /**
     * 加载分析标签页数据
     */
    async loadAnalyticsTab(tabType) {
        try {
            switch (tabType) {
                case 'forecast':
                    await this.loadForecastData();
                    break;
                case 'optimization':
                    await this.loadOptimizationData();
                    break;
                case 'supplier':
                    await this.loadSupplierData();
                    break;
                case 'trends':
                    await this.loadTrendsData();
                    break;
            }
        } catch (error) {
            console.error(`加载${tabType}数据失败:`, error);
        }
    }
    
    /**
     * 加载需求预测数据
     */
    async loadForecastData() {
        const data = await window.apiClient.getDemandForecast();
        // 更新预测图表和数据
        this.updateForecastContent(data);
    }
    
    /**
     * 加载库存优化数据
     */
    async loadOptimizationData() {
        const data = await window.apiClient.getInventoryOptimization();
        // 更新优化建议
        this.updateOptimizationContent(data);
    }
    
    /**
     * 加载供应商数据
     */
    async loadSupplierData() {
        const data = await window.apiClient.getSupplierPerformance();
        // 更新供应商绩效
        this.updateSupplierContent(data);
    }
    
    /**
     * 加载趋势数据
     */
    async loadTrendsData() {
        const data = await window.apiClient.getMarketTrends();
        // 更新市场趋势
        this.updateTrendsContent(data);
    }
    
    /**
     * 更新预测内容
     */
    updateForecastContent(data) {
        const container = document.getElementById('forecastContent');
        if (container && data) {
            // 这里可以根据实际数据结构更新内容
            container.innerHTML = `
                <div class="forecast-summary">
                    <h4>需求预测摘要</h4>
                    <p>基于历史数据和市场趋势，预测未来30天的需求变化。</p>
                </div>
                <div class="forecast-chart">
                    <canvas id="forecastChart"></canvas>
                </div>
            `;
            
            // 创建预测图表
            if (data.chartData) {
                window.chartManager.createInventoryChart('forecastChart', data.chartData);
            }
        }
    }
    
    /**
     * 更新优化内容
     */
    updateOptimizationContent(data) {
        const container = document.getElementById('optimizationContent');
        if (container && data) {
            container.innerHTML = `
                <div class="optimization-summary">
                    <h4>库存优化建议</h4>
                    <div class="optimization-recommendations">
                        ${data.recommendations?.map(rec => `
                            <div class="recommendation-item">
                                <h5>${rec.title}</h5>
                                <p>${rec.description}</p>
                                <span class="priority priority-${rec.priority}">${rec.priorityText}</span>
                            </div>
                        `).join('') || '<p>暂无优化建议</p>'}
                    </div>
                </div>
            `;
        }
    }
    
    /**
     * 更新供应商内容
     */
    updateSupplierContent(data) {
        const container = document.getElementById('supplierContent');
        if (container && data) {
            container.innerHTML = `
                <div class="supplier-performance">
                    <h4>供应商绩效分析</h4>
                    <div class="supplier-chart">
                        <canvas id="supplierChart"></canvas>
                    </div>
                </div>
            `;
            
            // 创建供应商绩效雷达图
            if (data.chartData) {
                window.chartManager.createRadarChart('supplierChart', data.chartData);
            }
        }
    }
    
    /**
     * 更新趋势内容
     */
    updateTrendsContent(data) {
        const container = document.getElementById('trendsContent');
        if (container && data) {
            container.innerHTML = `
                <div class="market-trends">
                    <h4>市场趋势分析</h4>
                    <div class="trends-chart">
                        <canvas id="trendsChart"></canvas>
                    </div>
                </div>
            `;
            
            // 创建趋势图表
            if (data.chartData) {
                window.chartManager.createInventoryChart('trendsChart', data.chartData);
            }
        }
    }
    
    /**
     * 更新质量仪表板
     */
    updateQualityDashboard(data) {
        if (!data) return;
        
        const container = document.getElementById('qualityDashboard');
        if (container) {
            container.innerHTML = `
                <div class="quality-metrics">
                    <div class="metric-card">
                        <div class="metric-value">${data.qualityScore || 0}%</div>
                        <div class="metric-label">质量得分</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-value">${data.defectRate || 0}%</div>
                        <div class="metric-label">缺陷率</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-value">${data.inspectionCount || 0}</div>
                        <div class="metric-label">检验次数</div>
                    </div>
                    <div class="metric-card">
                        <div class="metric-value">${data.capaCount || 0}</div>
                        <div class="metric-label">CAPA数量</div>
                    </div>
                </div>
                <div class="quality-chart">
                    <canvas id="qualityChart"></canvas>
                </div>
            `;
            
            // 创建质量图表
            if (data.chartData) {
                window.chartManager.createPieChart('qualityChart', data.chartData);
            }
        }
    }
    
    /**
     * 显示商品详情
     */
    async showItemDetail(itemId) {
        try {
            const data = await window.apiClient.get(`/inventory/${itemId}`);
            this.showModal('商品详情', this.renderItemDetail(data));
        } catch (error) {
            console.error('获取商品详情失败:', error);
        }
    }
    
    /**
     * 显示订单详情
     */
    async showOrderDetail(orderId) {
        try {
            const data = await window.apiClient.getOrderDetail(orderId);
            this.showModal('订单详情', this.renderOrderDetail(data));
        } catch (error) {
            console.error('获取订单详情失败:', error);
        }
    }
    
    /**
     * 渲染商品详情
     */
    renderItemDetail(data) {
        return `
            <div class="item-detail">
                <div class="detail-section">
                    <h4>基本信息</h4>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <label>SKU:</label>
                            <span>${data.sku || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>商品名称:</label>
                            <span>${data.name || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>类别:</label>
                            <span>${data.category || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>当前库存:</label>
                            <span>${data.quantity || 0} ${data.unit || ''}</span>
                        </div>
                    </div>
                </div>
                <div class="detail-section">
                    <h4>库存状态</h4>
                    <div class="status-info">
                        <span class="status-badge status-${data.status}">${data.statusText || '-'}</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 渲染订单详情
     */
    renderOrderDetail(data) {
        return `
            <div class="order-detail">
                <div class="detail-section">
                    <h4>订单信息</h4>
                    <div class="detail-grid">
                        <div class="detail-item">
                            <label>订单号:</label>
                            <span>${data.orderNumber || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>客户:</label>
                            <span>${data.customer || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>订单日期:</label>
                            <span>${data.date || '-'}</span>
                        </div>
                        <div class="detail-item">
                            <label>订单金额:</label>
                            <span>¥${data.amount || 0}</span>
                        </div>
                    </div>
                </div>
                <div class="detail-section">
                    <h4>订单状态</h4>
                    <div class="status-info">
                        <span class="status-badge status-${data.status}">${data.statusText || '-'}</span>
                    </div>
                </div>
            </div>
        `;
    }
    
    /**
     * 显示模态框
     */
    showModal(title, content) {
        const modal = document.getElementById('detailModal');
        const modalTitle = document.getElementById('modalTitle');
        const modalContent = document.getElementById('modalContent');
        
        if (modal && modalTitle && modalContent) {
            modalTitle.textContent = title;
            modalContent.innerHTML = content;
            modal.style.display = 'flex';
            document.body.style.overflow = 'hidden';
        }
    }
    
    /**
     * 关闭模态框
     */
    closeModal() {
        const modal = document.getElementById('detailModal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    }
    
    /**
     * 显示错误信息
     */
    showError(message) {
        window.apiClient.showNotification(message, 'error');
    }
    
    /**
     * 刷新当前模块
     */
    async refreshCurrentModule() {
        await this.loadModuleData(this.currentModule);
    }
    

    
    /**
     * 更新仓库选择器
     */
    updateWarehouseSelect(warehouses) {
        const select = document.getElementById('warehouseSelect');
        if (select && warehouses) {
            select.innerHTML = '<option value="">所有仓库</option>' +
                warehouses.map(wh => `<option value="${wh.id}">${wh.name}</option>`).join('');
        }
    }
    
    /**
     * 更新类别选择器
     */
    updateCategorySelect(categories) {
        const select = document.getElementById('categorySelect');
        if (select && categories) {
            select.innerHTML = '<option value="">所有类别</option>' +
                categories.map(cat => `<option value="${cat.id}">${cat.name}</option>`).join('');
        }
    }
}

// 计划管理模块初始化
function initPlanningModule() {
    // 初始化子导航标签页切换
    const navItems = document.querySelectorAll('#planning-content .nav-item');
    const tabContents = document.querySelectorAll('#planning-content .tab-content');
    
    navItems.forEach(item => {
        item.addEventListener('click', function() {
            const tabId = this.getAttribute('data-tab');
            
            // 移除所有活动状态
            navItems.forEach(nav => nav.classList.remove('active'));
            tabContents.forEach(tab => tab.classList.remove('active'));
            
            // 添加当前活动状态
            this.classList.add('active');
            document.getElementById(tabId).classList.add('active');
            
            // 初始化对应标签页的图表
            initPlanningCharts(tabId);
        });
    });
    
    // 初始化默认标签页的图表
    initPlanningCharts('demand');
}

// 初始化计划管理图表
function initPlanningCharts(tabId) {
    switch(tabId) {
        case 'demand':
            initDemandChart();
            break;
        case 'capacity':
            initCapacityChart();
            break;
        case 'inventory':
            initInventoryChart();
            break;
        case 'sop':
            initSopChart();
            break;
    }
}

// 需求预测图表
function initDemandChart() {
    const canvas = document.getElementById('demandChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    
    // 清除之前的图表
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    // 简单的模拟图表
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#f0f8ff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    ctx.strokeStyle = '#1976d2';
    ctx.lineWidth = 2;
    ctx.beginPath();
    
    const points = [
        {x: 50, y: 200},
        {x: 150, y: 150},
        {x: 250, y: 180},
        {x: 350, y: 120},
        {x: 450, y: 100},
        {x: 550, y: 140}
    ];
    
    points.forEach((point, index) => {
        if (index === 0) {
            ctx.moveTo(point.x, point.y);
        } else {
            ctx.lineTo(point.x, point.y);
        }
    });
    
    ctx.stroke();
    
    // 添加数据点
    ctx.fillStyle = '#1976d2';
    points.forEach(point => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI);
        ctx.fill();
    });
    
    // 添加标题
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.fillText('需求预测趋势', 20, 30);
}

// 产能利用图表
function initCapacityChart() {
    const canvas = document.getElementById('capacityChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    // 绘制柱状图
    const data = [85, 95, 90, 78, 88];
    const labels = ['生产线A', '生产线B', '包装线', '质检线', '仓储'];
    const barWidth = 60;
    const spacing = 80;
    
    ctx.fillStyle = '#f0f8ff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    data.forEach((value, index) => {
        const x = 50 + index * spacing;
        const height = (value / 100) * 200;
        const y = 250 - height;
        
        // 绘制柱子
        ctx.fillStyle = value > 90 ? '#f44336' : value > 80 ? '#ff9800' : '#4caf50';
        ctx.fillRect(x, y, barWidth, height);
        
        // 添加数值标签
        ctx.fillStyle = '#333';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(value + '%', x + barWidth/2, y - 10);
        ctx.fillText(labels[index], x + barWidth/2, 270);
    });
    
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('产能利用率分析', 20, 30);
}

// 库存周转图表
function initInventoryChart() {
    const canvas = document.getElementById('inventoryChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#f0f8ff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制饼图
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 80;
    
    const data = [
        {label: '原材料', value: 35, color: '#1976d2'},
        {label: '半成品', value: 25, color: '#4caf50'},
        {label: '成品', value: 40, color: '#ff9800'}
    ];
    
    let currentAngle = 0;
    
    data.forEach(item => {
        const sliceAngle = (item.value / 100) * 2 * Math.PI;
        
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.arc(centerX, centerY, radius, currentAngle, currentAngle + sliceAngle);
        ctx.closePath();
        ctx.fillStyle = item.color;
        ctx.fill();
        
        // 添加标签
        const labelAngle = currentAngle + sliceAngle / 2;
        const labelX = centerX + Math.cos(labelAngle) * (radius + 30);
        const labelY = centerY + Math.sin(labelAngle) * (radius + 30);
        
        ctx.fillStyle = '#333';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(item.label, labelX, labelY);
        ctx.fillText(item.value + '%', labelX, labelY + 15);
        
        currentAngle += sliceAngle;
    });
    
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('库存结构分析', 20, 30);
}

// S&OP执行图表
function initSopChart() {
    const canvas = document.getElementById('sopChart');
    if (!canvas) return;
    
    const ctx = canvas.getContext('2d');
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    
    canvas.width = canvas.offsetWidth;
    canvas.height = 300;
    
    ctx.fillStyle = '#f0f8ff';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // 绘制雷达图
    const centerX = canvas.width / 2;
    const centerY = canvas.height / 2;
    const radius = 100;
    const metrics = ['销售达成', '库存优化', '产能利用', '成本控制', '客户满意'];
    const values = [92, 88, 95, 85, 90];
    
    // 绘制网格
    ctx.strokeStyle = '#ddd';
    ctx.lineWidth = 1;
    
    for (let i = 1; i <= 5; i++) {
        ctx.beginPath();
        const r = (radius / 5) * i;
        
        for (let j = 0; j < metrics.length; j++) {
            const angle = (j * 2 * Math.PI) / metrics.length - Math.PI / 2;
            const x = centerX + Math.cos(angle) * r;
            const y = centerY + Math.sin(angle) * r;
            
            if (j === 0) {
                ctx.moveTo(x, y);
            } else {
                ctx.lineTo(x, y);
            }
        }
        ctx.closePath();
        ctx.stroke();
    }
    
    // 绘制轴线
    for (let i = 0; i < metrics.length; i++) {
        const angle = (i * 2 * Math.PI) / metrics.length - Math.PI / 2;
        ctx.beginPath();
        ctx.moveTo(centerX, centerY);
        ctx.lineTo(centerX + Math.cos(angle) * radius, centerY + Math.sin(angle) * radius);
        ctx.stroke();
        
        // 添加标签
        const labelX = centerX + Math.cos(angle) * (radius + 20);
        const labelY = centerY + Math.sin(angle) * (radius + 20);
        ctx.fillStyle = '#333';
        ctx.font = '12px Arial';
        ctx.textAlign = 'center';
        ctx.fillText(metrics[i], labelX, labelY);
    }
    
    // 绘制数据线
    ctx.strokeStyle = '#1976d2';
    ctx.fillStyle = 'rgba(25, 118, 210, 0.2)';
    ctx.lineWidth = 2;
    ctx.beginPath();
    
    for (let i = 0; i < values.length; i++) {
        const angle = (i * 2 * Math.PI) / values.length - Math.PI / 2;
        const r = (values[i] / 100) * radius;
        const x = centerX + Math.cos(angle) * r;
        const y = centerY + Math.sin(angle) * r;
        
        if (i === 0) {
            ctx.moveTo(x, y);
        } else {
            ctx.lineTo(x, y);
        }
    }
    
    ctx.closePath();
    ctx.fill();
    ctx.stroke();
    
    ctx.fillStyle = '#333';
    ctx.font = '14px Arial';
    ctx.textAlign = 'left';
    ctx.fillText('S&OP执行雷达图', 20, 30);
}

    /**
     * 更新采购图表
     */
    updateProcurementCharts(data) {
        if (!data) return;
        
        // 更新采购绩效图表
        const chartContainer = document.querySelector('#procurementChart');
        if (chartContainer && data.chartData) {
            this.renderChart(chartContainer, data.chartData, 'procurement');
        }
        
        // 更新采购统计
        const statsContainer = document.querySelector('#procurementStats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.stats.totalSuppliers || 0}</div>
                    <div class="stat-label">供应商总数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.stats.activeOrders || 0}</div>
                    <div class="stat-label">活跃采购订单</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">¥${data.stats.totalValue || 0}</div>
                    <div class="stat-label">采购总额</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新供应商表格
     */
    updateSupplierTable(data) {
        const tbody = document.querySelector('#supplierTable tbody');
        if (!tbody || !Array.isArray(data)) return;
        
        tbody.innerHTML = data.map(supplier => {
            // 确定状态
            let status = 'active';
            let statusText = '活跃';
            if (supplier.credit_rating < 3) {
                status = 'warning';
                statusText = '关注';
            } else if (supplier.credit_rating < 2) {
                status = 'danger';
                statusText = '风险';
            }
            
            return `
                <tr onclick="app.showSupplierDetail('${supplier.supplier_id}')" style="cursor: pointer;">
                    <td>${supplier.supplier_name}</td>
                    <td>${supplier.product_categories ? supplier.product_categories.join(', ') : '未分类'}</td>
                    <td><span class="status-badge status-${status}">${statusText}</span></td>
                    <td>${supplier.credit_rating}/5</td>
                    <td>¥${supplier.total_amount || 0}</td>
                    <td>${supplier.lead_time_days}天</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 更新生产图表
     */
    updateProductionCharts(data) {
        if (!data) return;
        
        // 更新生产效率图表
        const chartContainer = document.querySelector('#productionChart');
        if (chartContainer && data.chartData) {
            this.renderChart(chartContainer, data.chartData, 'production');
        }
        
        // 更新生产统计
        const statsContainer = document.querySelector('#productionStats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.stats.dailyOutput || 0}</div>
                    <div class="stat-label">日产量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.stats.efficiency || 0}%</div>
                    <div class="stat-label">生产效率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.stats.qualityRate || 0}%</div>
                    <div class="stat-label">合格率</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新生产订单
     */
    updateProductionOrders(data) {
        const tbody = document.querySelector('#productionOrderTable tbody');
        if (!tbody || !Array.isArray(data)) return;
        
        tbody.innerHTML = data.map(order => {
            // 确定状态显示
            let statusClass = 'active';
            let statusText = '进行中';
            
            switch(order.status) {
                case 'PENDING':
                    statusClass = 'warning';
                    statusText = '待开始';
                    break;
                case 'IN_PROGRESS':
                    statusClass = 'active';
                    statusText = '进行中';
                    break;
                case 'COMPLETED':
                    statusClass = 'success';
                    statusText = '已完成';
                    break;
                case 'CANCELLED':
                    statusClass = 'danger';
                    statusText = '已取消';
                    break;
                default:
                    statusClass = 'secondary';
                    statusText = order.status;
            }
            
            return `
                <tr onclick="app.showProductionOrderDetail('${order.order_id}')" style="cursor: pointer;">
                    <td>${order.order_number}</td>
                    <td>${order.product_name}</td>
                    <td>${order.quantity} ${order.unit}</td>
                    <td><span class="status-badge status-${statusClass}">${statusText}</span></td>
                    <td>${order.progress}%</td>
                    <td>${order.planned_end_date}</td>
                </tr>
            `;
        }).join('');
    }
    
    /**
     * 更新配送图表
     */
    updateDeliveryCharts(data) {
        if (!data) return;
        
        // 更新配送绩效图表
        const chartContainer = document.querySelector('#deliveryChart');
        if (chartContainer && data.chartData) {
            this.renderChart(chartContainer, data.chartData, 'delivery');
        }
        
        // 更新配送统计
        const statsContainer = document.querySelector('#deliveryStats');
        if (statsContainer && data.stats) {
            statsContainer.innerHTML = `
                <div class="stat-item">
                    <div class="stat-value">${data.stats.totalShipments || 0}</div>
                    <div class="stat-label">总发货量</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.stats.onTimeRate || 0}%</div>
                    <div class="stat-label">准时交付率</div>
                </div>
                <div class="stat-item">
                    <div class="stat-value">${data.stats.avgDeliveryTime || 0}天</div>
                    <div class="stat-label">平均配送时间</div>
                </div>
            `;
        }
    }
    
    /**
     * 更新物流状态
     */
    updateLogisticsStatus(data) {
        const tbody = document.querySelector('#logisticsTable tbody');
        if (!tbody || !Array.isArray(data)) return;
        
        tbody.innerHTML = data.map(shipment => {
            // 确定状态显示
            let statusClass = 'active';
            let statusText = shipment.status;
            
            switch(shipment.status) {
                case '待发货':
                    statusClass = 'warning';
                    statusText = '待发货';
                    break;
                case '运输中':
                    statusClass = 'active';
                    statusText = '运输中';
                    break;
                case '已签收':
                    statusClass = 'success';
                    statusText = '已签收';
                    break;
                case '异常':
                    statusClass = 'danger';
                    statusText = '异常';
                    break;
                default:
                    statusClass = 'secondary';
                    statusText = shipment.status;
            }
            
            // 格式化日期
            const estimatedDate = shipment.estimated_arrival ? 
                new Date(shipment.estimated_arrival).toLocaleDateString('zh-CN') : 
                '未知';
            
            return `
                <tr onclick="app.showShipmentDetail('${shipment.shipment_id}')" style="cursor: pointer;">
                    <td>${shipment.tracking_number}</td>
                    <td>${shipment.destination}</td>
                    <td><span class="status-badge status-${statusClass}">${statusText}</span></td>
                    <td>${estimatedDate}</td>
                    <td>${shipment.carrier_name}</td>
                </tr>
            `;
        }).join('');
    }
}

// 全局函数
window.viewDetails = function(id) {
    console.log('查看详情:', id);
    // TODO: 实现详情查看功能
    alert(`查看详情: ${id}`);
};

window.exportData = function() {
    console.log('导出数据');
    // TODO: 实现数据导出功能
    alert('导出功能开发中...');
};

// 页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    window.app = new SupplyChainApp();
});

// 页面卸载时清理资源
window.addEventListener('beforeunload', () => {
    if (window.app) {

    }
});